<template>
  <div class="role-with-permit-container">
    <!-- 搜索区域 -->
    <div class="search-bar">
      <el-button type="text">员工姓名/电话</el-button>
      <el-input
          v-model="searchForm.staffInfo"
          placeholder="请输入员工姓名/电话"
          class="search-input"
          clearable
          @keyup.enter="handleSearch"
      />
      <el-button type="text">门店名称</el-button>
      <el-input
          v-model="searchForm.storeName"
          placeholder="请输入门店名称"
          class="search-input"
          clearable
          @keyup.enter="handleSearch"
      />
      <el-button type="primary" @click="handleSearch">
        <el-icon><Search /></el-icon>
        搜索
      </el-button>
    </div>

    <!-- 员工列表 -->
    <el-table
        :data="staffList"
        border
        stripe
        style="width: 100%; margin-top: 16px"
    >
      <el-table-column type="index" label="序号" width="80" />
      <el-table-column prop="staffAccount" label="员工账号" width="140" />
      <el-table-column prop="staffName" label="员工姓名" width="120" />
      <el-table-column prop="phone" label="员工电话" width="140" />
      <el-table-column prop="role.roleName" label="员工角色" width="120" />
      <el-table-column prop="storeDto.storeName" label="门店名称" width="160" />
      <el-table-column label="操作" width="160">
        <template #default="scope">
          <el-button
              type="text"
              @click="handleEditPermission(scope.row)"
              text-color="#409EFF"
          >
            修改角色权限
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <div class="pagination-container">
      <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 角色权限编辑弹窗 -->
    <el-dialog
        v-model="dialogVisible"
        title="选择角色权限"
        :width="650"
        :before-close="handleDialogClose"
    >
      <div class="permission-dialog-content">
        <el-form ref="permissionForm" :model="formData" label-width="90px">
          <!-- 角色选择 -->
          <el-form-item label="选择角色" required>
            <el-select
                v-model="formData.roleId"
                placeholder="请选择角色"
                @change="loadRolePermissions(formData.roleId)"
                clearable
            >
              <el-option
                  v-for="role in roleList"
                  :key="role.id"
                  :label="role.roleName"
                  :value="role.id"
              />
            </el-select>
          </el-form-item>

          <!-- 权限列表 -->
          <el-form-item label="权限设置">
            <div v-if="formData.roleId && permissionList.length > 0" class="permission-list">
              <el-checkbox-group v-model="formData.permissionIds">
                <el-checkbox
                    v-for="perm in permissionList"
                    :key="perm.id"
                    :value="perm.id"
                    :label="perm.permissionName"
                    class="permission-item"
                >
                  {{ perm.permissionName }}
                </el-checkbox>
              </el-checkbox-group>
            </div>
            <div v-else-if="formData.roleId" class="empty-state">
              <el-empty description="该角色暂无可用权限" />
            </div>
            <div v-else class="empty-state">
              <el-empty description="请先选择角色" />
            </div>
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="savePermissionSetting">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search } from '@element-plus/icons-vue';
import axios from "axios";

// 搜索表单数据
const searchForm = reactive({
  staffInfo: '',  // 员工姓名/电话搜索
  storeName: ''   // 门店名称搜索
});

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 员工列表数据
const staffList = ref([
  {
    "id": 1,
    "staffAccount": "admin001",
    "staffName": "李店长",
    "phone": "13811111111",
    "roleId": 4,
    "role": {
      "id": 4,
      "roleName": "店长",
      "description": "管理门店所有事务"
    },
    "storeId": 1,
    "storeDto": {
      "storeId": 1,
      "storeName": "极速汽车服务中心"
    }
  }
]);

// 弹窗状态
const dialogVisible = ref(false);

// 表单数据
const formData = reactive({
  staffId: null,       // 当前编辑的员工ID
  roleId: null,        // 选中的角色ID
  permissionIds: []    // 选中的权限ID数组
});

// 角色和权限数据
const roleList = ref([
  {
    "id": 1,
    "roleName": "系统管理员",
    "description": "拥有系统所有权限"
  }
]);
const permissionList = ref([
  {
    "id": 8,
    "permissionName": "预约管理"
  },
]);
const currentStaff = ref(null);

// 模拟API请求函数 - 实际项目中替换为真实接口调用
const getStaffList=()=>{
  axios.post(`/carcenter-service-personnel/staff/getStaffListWithSearchDto`,searchForm)
      .then(resp => {
        staffList.value=resp.data.data;
        pagination.total=resp.data.data.length;
      })

}
const getRoles=()=>{
  axios.get(`/carcenter-service-personnel/roles/getRoleList`)
      .then(resp => {
        roleList.value=resp.data.data;
      })
}

const modifyPermissionByRoleId=(roleId,permissionIds)=>{
  axios.put(`/carcenter-service-personnel/role-permissions/modifyPermissionsWithRoleId/${roleId}`,permissionIds).then(resp => {
    ElMessage.success(resp.data.message);
  }).catch(err=>{
    ElMessage.error(err.response.data);
  })
}

const savePermission=(data)=>{
  axios.put(`/carcenter-service-personnel/staff/modifyRoleByStaffId/${data.staffId}/${data.roleId}`).then(resp => {
    ElMessage.success(resp.data.message);
    if (resp.data.code === 200) {
      modifyPermissionByRoleId(data.roleId,data.permissionIds);
    }
  }).catch(err=>{
    ElMessage.error(err.response.data);
  })


}

const getRolePermissions=(roleId)=>{
  axios.get(`/carcenter-service-personnel/permissions/getPermissionsByRoleId/${roleId}`).then(resp => {
    permissionList.value = resp.data.data;
    // 默认选中所有权限
    formData.permissionIds = permissionList.value.map(perm => perm.id);
  })
}




// 初始化组件
onMounted(async () => {
  // 加载角色列表
  getRoles();

  // 加载员工列表
  getStaffList();
});




// 搜索按钮点击
const handleSearch = () => {
  pagination.currentPage = 1;
  getStaffList();
};

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.pageSize = size;
  getStaffList();
};

// 当前页改变
const handleCurrentChange = (page) => {
  pagination.currentPage = page;
  getStaffList();
};

// 打开编辑弹窗
const handleEditPermission = (staff) => {
  currentStaff.value = staff;
  formData.staffId = staff.id;

  // 重置表单数据
  formData.roleId = null;
  formData.permissionIds = [];
  permissionList.value = [];

  // 打开弹窗
  dialogVisible.value = true;
};

// 加载角色对应的权限
const loadRolePermissions = async (roleId) => {
  if (!roleId) {
    permissionList.value = [];
    formData.permissionIds = [];
    return;
  }
  getRolePermissions(roleId);

};

// 保存权限设置
const savePermissionSetting = async () => {
  if (!formData.roleId) {
    ElMessage.warning('请选择角色');
    return;
  }

  if (!formData.permissionIds.length) {
    ElMessageBox.confirm(
        '未选择任何权限，确定要保存吗？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    ).then(async () => {
      await saveSetting();
    });
    return;
  }

  await saveSetting();
};

// 实际保存逻辑
const saveSetting = async () => {
  try {
    const data = {
      staffId: formData.staffId,
      roleId: formData.roleId,
      permissionIds: formData.permissionIds
    };

    await savePermission(data);
    ElMessage.success('保存成功');

    // 更新当前员工的角色显示
    if (currentStaff.value) {
      const role = roleList.value.find(r => r.id === formData.roleId);
      if (role) {
        currentStaff.value.roleName = role.roleName;
        // 刷新当前行显示
        staffList.value = [...staffList.value];
      }
    }

    dialogVisible.value = false;
  } catch (error) {
    ElMessage.error('保存失败');
    console.error(error);
  }
};

// 关闭弹窗
const handleDialogClose = () => {
  dialogVisible.value = false;
  // 重置表单
  formData.roleId = null;
  formData.permissionIds = [];
  permissionList.value = [];
  currentStaff.value = null;
};
</script>

<style scoped>
.role-with-permit-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  min-height: calc(100vh - 40px);
}

.search-bar {
  display: flex;
  gap: 16px;
  align-items: center;
  flex-wrap: wrap;
}

.search-input {
  width: 280px;
}

.pagination-container {
  margin-top: 16px;
  text-align: right;
}

.permission-dialog-content {
  max-height: 400px;
  overflow-y: auto;
  padding-right: 10px;
}

.permission-list {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-top: 8px;
}

.permission-item {
  width: 48%;
}

.empty-state {
  margin-top: 10px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .search-input {
    width: 100%;
  }

  .permission-item {
    width: 100%;
  }
}
</style>